﻿package {
	import flash.display.*;
	import flash.text.*;
	import flash.events.*;
	import flash.external.*;
	import flash.net.*;
	import flash.system.*;
	import flash.filters.*;
	import json.*;
	import caurina.transitions.Tweener;
	public class Bar extends Sprite {
		private var stageW:Number;
		private var stageH:Number;
		private var bar:Object;
		//主绘图层
		private var main:Sprite;
		//Tip层
		private var tip:Tip;
		//标记格式
		private var tagFormat:TextFormat;
		//首次运行
		private var one:Boolean = true;
		public function Bar() {
			stage.scaleMode = "noScale";
			stage.align = "topLeft";
			stage.addEventListener(Event.RESIZE, resizeHd);
			//添加主绘图层
			main = new Sprite();
			addChild(main);
			//添加Tip层
			tip = new Tip(100, 0);
			addChild(tip);
			//
			init();
		}
		private function init():void {
			var data:String = cV("data");
			if (data) {
				//O.o(str);
				parseData(data);
			} else {
				var url:String = cV("url");
				if (!url) {
					url = "bar_data.txt";
				}
				var dataLoader:URLLoader = new URLLoader();
				dataLoader.load(new URLRequest(url));
				dataLoader.addEventListener(IOErrorEvent.IO_ERROR, errorHd);
				dataLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHd);
				dataLoader.addEventListener(Event.COMPLETE, completeHd);
			}
		}
		private function errorHd(e:Event):void {

		}
		private function completeHd(e:Event):void {
			var str:String = e.target.data;
			if (str) {
				//O.o(str);
				//过滤注释行
				str = str.replace(/\/\/.*\s/g,"");
				//过滤回车换行
				str = str.replace(/\n|\r/g,"");
				//O.o(str);
				parseData(str);
			}
		}
		//解析JSON数据
		private function parseData(str:String):void {
			try {
				bar = new JSONDecoder(str).getValue();
				//
				//O.o(bar.max);
				layout();
			} catch (e:Error) {
				O.o(e);
			}
		}
		private function resizeHd(e:Event):void {
			one = false;
			layout();
		}
		//开始布局绘图
		private function layout():void {
			stageW = stage.stageWidth;
			stageH = stage.stageHeight;
			//
			drawAll();
		}
		private function clearAll():void {
			while (main.numChildren) {
				main.removeChildAt(0);
			}
		}
		private function drawAll():void {
			//清除所有
			clearAll();
			//---------------------------------------------------------------------
			tagFormat = gF("Verdana",11,parseInt(bar.color.replace(/#/g, "0x")));
			//O.o(bar.ltrb);
			var left:Number = bar.ltrb[0];
			var top:Number = bar.ltrb[1];
			var right:Number = bar.ltrb[2];
			var bottom:Number = bar.ltrb[3];
			//
			var bx:Number = left;
			var by:Number = top;
			var bw:Number = stageW - left - right;
			var bh:Number = stageH - top - bottom;
			//画边框
			var box:Sprite = new Sprite();
			box.graphics.lineStyle(1, 0xcccccc, 1);
			box.graphics.drawRect(bx, by, bw, bh);
			//画x轴标记
			box.graphics.lineStyle(1, 0xcccccc, 0.5);
			var xtag:Array = bar.xtag;
			var xl:int = xtag.length;
			//至少2个以上
			if (xl > 1) {
				//每分宽度
				var xw:Number = bw / (xl - 1);
				for (var i:int = 0; i< xl; i++) {
					var xx:Number = left + xw * i;
					box.graphics.moveTo(xx, top);
					box.graphics.lineTo(xx, top + bh);
					var align:String = "center";
					if (i == xl - 1) {
						align = "right";
					}
					var valign:String = "top";
					var xtf:TextField = getLabel(xtag[i], xx, top + bh, tagFormat, align, valign);
					box.addChild(xtf);
				}
			}
			main.addChild(box);
			//=================================================
			//画横条及y轴标记
			var list:Array = bar.list;
			var ll:int = list.length;
			//最小值
			var min:Number = bar.min;
			if (isNaN(min)) {
				min = 0;
			}
			//最大值
			var max:Number = bar.max;
			if (isNaN(max)) {
				max = parseInt(xtag[xl - 1]);
			}
			//理论行高度
			var d:Number = bh / ll;
			//间距所占比例
			var v:Number = bar.dis_rate?bar.dis_rate:0.2;
			//间距高度
			var dv:Number = d * v;
			//实际横条高
			var dh:Number = (bh - (ll + 1) * dv)/ ll;
			//=========
			//平均值设置
			var average:Boolean = false;
			var ac:Number;
			var atw:Number;
			if (bar.average) {
				average = true;
				ac = parseInt(bar.average_style.replace(/#/g, "0x"));
				atw = bw * (parseFloat(bar.average) - min) / (max - min);
			}
			//=========
			for (var j:int = 0; j < ll; j++) {
				var b:Sprite = new Sprite();
				b.buttonMode = true;
				var c:Number = parseInt(list[j][1].replace(/#/g, "0x"));
				//
				var tx:Number = left;
				var ty:Number = top + dv + (dh + dv) * j;
				var tw:Number = bw * (parseFloat(list[j][2]) - min) / (max - min);
				var th:Number = dh;
				//
				b.graphics.beginFill(c);
				b.graphics.drawRect(0, 0, tw, th);
				b.graphics.endFill();
				//如果存在平均值设置,修正图形样式
				if (average) {
					b.graphics.beginFill(ac);
					b.graphics.drawRect(0, 0, atw, th);
					b.graphics.endFill();
				}
				//
				b.x = tx;
				b.y = ty;
				b.filters = tip.gS(0, 0.3);
				//
				b.name = "b__" + j;
				b.addEventListener(MouseEvent.MOUSE_OVER, overHd);
				b.addEventListener(MouseEvent.MOUSE_OUT, outHd);
				b.addEventListener(MouseEvent.CLICK,clickHd);
				main.addChild(b);
				//渐变效果
				if (one && bar.show_tween) {
					b.scaleX = 0.1;
					Tweener.addTween(b, {scaleX:1, time:0.5, transition:"linear"});
				}
				//
				var ytf:TextField = getLabel(list[j][0], tx - 5, ty + th * 0.5, tagFormat, "right");
				main.addChild(ytf);
			}
		}
		//
		private function overHd(e:MouseEvent):void {
			e.target.alpha = 0.8;
			var i:int = parseInt(e.target.name.split("__")[1]);
			var str:String = bar.list[i][0];
			if (bar.show_number) {
				str += " (" + bar.list[i][2] + ")";
			}
			tip.show(str);
		}
		private function outHd(e:MouseEvent):void {
			e.target.alpha = 1;
			tip.hide();
		}
		//点击事件
		private function clickHd(e:MouseEvent):void {
			var i:int = parseInt(e.target.name.split("__")[1]);
			var str:String = bar.list[i][3];
			if (str && ExternalInterface.available) {
				try {
					ExternalInterface.call(str);
				} catch (e:Error) {
					O.o(e);
				}
			}
		}
		//新建标记
		private function getLabel(s:String, tx:int, ty:int, tf:TextFormat, align:String = "center", valign:String = "middle"):TextField {
			var label:TextField = new TextField();
			label.selectable = false;
			label.mouseEnabled = false;
			label.autoSize = "left";
			label.htmlText = s;
			label.setTextFormat(tf);
			if (align == "left") {
				label.x = tx;
			} else if (align == "right") {
				label.x = tx - label.textWidth;
			} else {
				label.x = tx - label.textWidth/2;
			}
			if (valign == "top") {
				label.y = ty;
			} else if (valign == "bottom") {
				label.y = ty - label.textHeight;
			} else {
				label.y = ty - label.textHeight/2;
			}
			return label;
		}
		//标记格式
		private function gF(font:String = "Verdana", size:Number = 12, color:Number = 0):TextFormat {
			var tf:TextFormat = new TextFormat();
			tf.font = font;
			tf.size = size;
			tf.color = color;
			return tf;
		}
		//读取传入参数
		public function cV(str:String):String {
			return this.root.loaderInfo.parameters[str];
		}
	}
}